<template>
	<view>
		<!-- #ifdef APP-PLUS -->
		<i class="iconfont icon-weixin2 text-3xl text-green" @click="app"></i>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<i class="iconfont icon-weixin2 text-3xl text-green" @click="mini"></i>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapActions
	} from 'vuex';

	export default {
		methods: {
			...mapActions('user', ['getCurrentUser']),
			//手机APP登录
			app() {
				let This = this;
				uni.login({
					provider: 'weixin',
					scopes: 'auth_user',
					success: function(loginRes) {
						console.log(loginRes);
						uni.getUserInfo({
							provider: 'weixin',
							async success(infoRes) {
								const res = await This.$api.post(`/wechat/app/login`, infoRes
									.userInfo)
									console.log(res);
								This.cacheUser(res.data.token)
							},
						});
					},
				});
			},
			//小程序登录
			mini() {
				const This = this;
				uni.getUserProfile({
					desc: '获取你的昵称、头像、地区及性别',
					async success(info) {
						uni.login({
							provider: 'weixin',
							async success(loginRes) {
								//完成后台登录并返回token
								const res = await This.$api.post(
									`/mini/login/${This.$config.mini.id}/${loginRes.code}`,
									info.userInfo);
									
								This.cacheUser(res.data.token);
							}
						})
					}
				})
			},
			//缓存TOKEN并获取用户资料
			async cacheUser(token) {
				uni.setStorageSync('token', token)
				await this.getCurrentUser()
				uni.reLaunch({
					url: '/pages/my/my'
				})
			}
		}
	}
</script>

<style>

</style>
